<template>
  <div class="">
    <label v-if="label" :class="{ 'g-form-item-label-required': isRequired }">
      {{ label }}
    </label>
    <div>
      <slot></slot>
      <div v-if="state === 'error'" class="g-form-item-message">
        {{ message }}
      </div>
    </div>
  </div>
</template>
<script>
import Emitter from "@/mixins/emitter.js";
import AsyncValidator from "async-validator";

export default {
  name: "gFormItem",
  mixins: [Emitter],
  inject: ["form"],
  props: {
    label: {
      type: String,
      default: "",
    },
    prop: {
      type: String,
    },
  },
  data() {
    return {
      isRequired: false,
      initialValue: "",
      state: "",
      message: "",
    };
  },
  mounted() {
    // 组件渲染时，将实例缓存在 Form 中
    if (this.prop) {
      // 如果没有传入 prop，则无需校验，也就无需缓存
      this.dispatch("gForm", "on-form-item-add", this);
      this.setRules();
    }
    this.initialValue = this.fieldValue;
  },
  beforeDestroy() {
    // 组件销毁前，将实例从 Form 的缓存中移除
    this.dispatch("gForm", "on-form-item-remove", this);
  },
  computed: {
    fieldValue() {
      return this.form.model[this.prop];
    },
  },
  methods: {
    onFieldBlur() {
      this.validate("blur");
    },
    onFieldChange() {
      this.validate("change");
    },
    setRules() {
      let rules = this.getRules();
      if (rules.length) {
        rules.every((rule) => {
          // 如果当前校验规则中有必填项，则标记出来
          this.isRequired = rule.required;
        });
      }
      this.$on("on-form-blur", this.onFieldBlur);
      this.$on("on-form-change", this.onFieldChange);
    },
    // 校验数据
    validate(trigger, callback = function () {}) {
      let rules = this.getTriggerRule(trigger);
      if (!rules || !rules.length) return true;
      // 设置状态为校验中
      this.state = "validating";
      // async-validator 库的调用方法
      let descriptor = {};
      descriptor[this.prop] = rules;
      const validator = new AsyncValidator(descriptor);
      let model = {};
      model[this.prop] = this.fieldValue;
      validator.validate(model, { firstFields: true }, (errors) => {
        this.state = !errors ? "success" : "error";
        this.message = errors ? errors[0].message : "";
        callback(this.message);
      });
    },
    // 获取校验规则
    getRules() {
      return [].concat(this.form.rules[this.prop] || []);
    },
    // 获取 trigger 类型的校验规则
    getTriggerRule(trigger) {
      const rules = this.getRules();
      return rules.filter(
        (r) => r.trigger && r.trigger.indexOf(trigger) !== -1
      );
    },
    // 重置数据
    resetField() {
      this.state = "";
      this.message = "";
      console.log(this);
      this.form.model[this.prop] = this.initialValue;
    },
  },
};
</script>

<style lang="scss" scoped>
.g-form-item-label-required:before {
  content: "*";
  color: red;
}
.g-form-item-message {
  color: red;
}
</style>
